﻿using System;
using System.Windows.Forms;
using SpeechLib;

namespace graduation_project.Voice_Recognition
{
    class SimulationRecongnition
    {
        private static SimulationRecongnition SimulationCom = null;
        //private SpSharedRecognizer shareRecognizer = new SpSharedRecognizer();    //共享性识别器
        private SpeechLib.SpSharedRecoContext SimulationShareRecoContext = null;   //共享识别器语境
        public ISpeechRecoGrammar SimulationShareRecoGrammar = null;       //共享识别器语法
        //private string str = null;
        private System.Windows.Forms.Control str;
        private string SimulationXml = "E://WorkSpace//c++//graduation project//graduation project//Xml//XMLFile2.xml";
        /// <summary>
        /// 语法识别初始化
        /// </summary>
        public void simulationRecongnitionInitialize()
        {
            try
            {
                SimulationShareRecoContext = new SpSharedRecoContext();
                //SimulationShareRecoContext = (SpSharedRecoContext)shareRecognizer.CreateRecoContext();
                SimulationShareRecoGrammar = SimulationShareRecoContext.CreateGrammar(1);     //为识别的语句创建语法器
                SimulationShareRecoGrammar.CmdLoadFromFile(SimulationXml, SpeechLoadOption.SLOStatic);
                //SimulationShareRecoContext.EventInterests = SpeechRecoEvents.SREAllEvents;
                SimulationShareRecoContext.Recognition += new _ISpeechRecoContextEvents_RecognitionEventHandler(StrRecognize);   //为上下文添加处理的函数
                // SimulationShareRecoGrammar.CmdSetRuleState(SimulationShareRecoGrammar.Rules.Item(0).Name,SpeechRuleState.SGDSInactive);
            }
            catch (Exception er)
            {
                MessageBox.Show("An  Error  Occured!", "Speech", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        //将识别的语句加载到文本框内
        public void StrRecognize(int Index, object obj, SpeechLib.SpeechRecognitionType type, SpeechLib.ISpeechRecoResult result)
        {
            str.Text += result.PhraseInfo.GetText(0, -1, true);
        }
        //语音识别开始
        public void BeginRec(Control strSimulation)
        {
            SimulationShareRecoGrammar.DictationSetState(SpeechRuleState.SGDSActive);
            str = strSimulation;
        }
        public void closeRec()
        {
            SimulationShareRecoGrammar.DictationSetState(SpeechRuleState.SGDSInactive);
        }
        //单实例
        public static SimulationRecongnition instance()
        {
            if (SimulationCom == null)
                SimulationCom = new SimulationRecongnition();
            return SimulationCom;
        }
    }
}
